<?php namespace App\Http\Controllers;

use App\ActivityBargain;
use App\ActivityBargainInitiate;
use App\ActivityBargainJoin;
use App\ActivityGroup;
use App\ActivityGroupAdd;
use App\ActivityGroupPrice;
use App\Admin;
use App\AdvertImg;
use App\Banner;
use App\BannerNav;
use App\BooksChapter;
use App\BooksInfo;
use App\ChargeAvailable;
use App\ChargeRecord;
use App\ChargeUsedRecord;
use App\Classify;
use App\Comment;
use App\CommentImg;
use App\Coupons;
use App\DiscountRule;
use App\DiscountSalesRule;
use App\DiscountXGoods;
use App\DistributionRule;
use App\Express;
use App\ExpressBlade;
use App\ExpressCustomFee;
use App\Goods;
use App\GoodsBanner;
use App\GoodsImg;
use App\GoodSpu;
use App\GoodsServiceLabel;
use App\GoodsSnapshot;
use App\GoodsSpu;
use App\Http\Controllers\Api\AudioController;
use App\Http\Controllers\Api\GameController;
use App\Http\Services\FileManager;
use App\OrderAddress;
use App\OrderRefund;
use App\QrCodes;
use App\ReturnAddress;
use App\Shops;
use App\ShowGoods;
use App\UserIntegralRecord;
use App\UserScore;
use App\UserScoreRecord;
use App\UserTotoalScore;
use DB;
use App\OrderItem;
use App\Orders;
use App\RechargePackage;
use App\User;
use App\UserAddress;
use App\UserInfo;
use App\UserSpendRecord;
use Illuminate\Contracts\Auth\Guard;
use Auth;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class AdminController extends Controller
{
    public function login(){
        return view('admin.login');
    }

    public function bannerList(){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $sysBanners = Banner::orderBy('sort','asc')->orderBy('created_at','desc')->get();

        return view('admin.banner-list',['banners'=>$sysBanners]);
    }

    public function bannerSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        $thatBanner = Banner::whereId($id)->first();

        return view('admin.banner-set',['banner'=>$thatBanner]);
    }

    public function advertImgList(){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $sysAdvertImg = AdvertImg::orderBy('sort','asc')->orderBy('created_at','desc')->get();

        return view('admin.advert-img-list',['advertImgs'=>$sysAdvertImg]);
    }

    public function advertImgSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        $thatAdvertImg = AdvertImg::whereId($id)->first();

        return view('admin.advert-img-set',['advertImg'=>$thatAdvertImg]);
    }

    public function userList(Request $request){
        if(Auth::guard("admin")->guest())
            return redirect(route('Admin.Home.login'));
        $keyword=$request->get('keyword');
        $users=User::orderBy("id","desc");
        if ($keyword){
            $ids=UserInfo::where('nickname','like','%'.trim($keyword).'%')->pluck('user_id')->toArray();
            $users=User::wherePhone(trim($keyword))->orWhereIn('id',$ids);
        }

        $users = $users->paginate(50);


        foreach($users as $user){
            /** @var User $user */
            $user->userInfo;
            $is_charge=ChargeAvailable::whereUserId($user->id)->first();
            if ($is_charge)
                $rule=DiscountRule::whereId($is_charge->discount_rule_id)->first();
            else
                $rule=false;
            $user->charge_available=$is_charge ? $is_charge->amount : 0;
            $user->discount_rule_name=$rule ? $rule->rule_name : '无折扣';
            $user->discount_id=$rule ? (int)$rule->id : 0;
        }
        $discount=DiscountRule::all();

        return view('admin.user-list',["users"=>$users,'keyword'=>$keyword,'discount'=>$discount]);
    }

    public function vipUserList(Request $request){
        if(Auth::guard("admin")->guest())
            return redirect(route('Admin.Home.login'));
        $keyword=$request->get('keyword');

        $uidS=ChargeAvailable::pluck('user_id')->toArray();
        $users=User::orderBy("id","desc");
        if ($keyword){
            $ids=UserInfo::where('nickname','like','%'.trim($keyword).'%')->pluck('user_id')->toArray();
            $users=User::wherePhone(trim($keyword))->orWhereIn('id',$ids);
        }

        $users = $users->whereIn('id',$uidS)->paginate(50);

        foreach($users as $user){
            /** @var User $user */
            $user->userInfo;
            $is_charge=ChargeAvailable::whereUserId($user->id)->first();
            if ($is_charge)
                $rule=DiscountRule::whereId($is_charge->discount_rule_id)->first();
            else
                $rule=false;
            $user->charge_available=$is_charge ? $is_charge->amount : 0;
            $user->discount_rule_name=$rule ? $rule->rule_name : '无折扣';
            $user->discount_id=$rule ? $rule->id : 0;
        }
        $discount=DiscountRule::all();

        return view('admin.user-list',["users"=>$users,'keyword'=>$keyword,'discount'=>$discount]);
    }

    public function adminList(Request $request)
    {
        if (Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        /** @var Admin $newAdmin */
        $newAdmins = Admin::orderBy('created_at', 'desc')->paginate(10);

        return view('admin.admin-list', ['admins' => $newAdmins]);
    }

    public function adminSet(Request $request)
    {
        if (Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        return view('admin.admin-set');
    }

    public function classifyList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $classifies = Classify::wherePid(0)->whereType('goods')->orderBy('sort','asc')->orderBy('created_at','desc')->paginate(20);
        if(count($classifies) > 0){
            foreach ($classifies as $classify){
                $allChildMenu = Classify::wherePid($classify->id)->whereType('goods')->orderBy('sort','asc')->orderBy('created_at','desc')->get();
                $classify->child = $allChildMenu;
                $classify->advert_img_url = FileManager::getImgUrl($classify->advert_img_id);

                $thatSection = Classify::whereId($classify->classify_id)->first();
                if($thatSection){
                    $classify->section_name = $thatSection->name;
                }else{
                    $classify->section_name = "-";
                }
            }
        }

        $sections = Classify::whereType("section")->get();

        return view('admin.classify-list',['classifies' => $classifies,"sections"=>$sections]);
    }

    public function goodsServiceLabelList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $classifies = GoodsServiceLabel::orderBy('sort','asc')->orderBy('created_at','desc')->get();

        return view('admin.goods-service-label-list',['classify' => $classifies]);
    }

    public function sectionList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $classifies = Classify::wherePid(0)->whereType('section')->orderBy('sort','asc')->orderBy('created_at','desc')->get();
        if(count($classifies) > 0){
            foreach ($classifies as $classify){
                $classify->img_url = FileManager::getImgUrl($classify->img_id);
            }
        }

        return view('admin.section-list',['classify' => $classifies]);
    }

    public function sectionSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var Classify $classify */
        $classify = Classify::whereId($id)->first();
        if($classify){
            $classify->img_url = FileManager::getImgUrl($classify->img_id);
        }

        $parentClassifys = Classify::wherePid(0)->whereType("goods")->get();
        if($classify){
            $goodsTwoClassify = Classify::whereId($classify->classify_id)->first();
            if($goodsTwoClassify){
                if($goodsTwoClassify->pid != 0 && !is_null($goodsTwoClassify->pid)){
                    $classify->classify_two_id = $classify->classify_id;
                    $classify->classify_id = $goodsTwoClassify->pid;

                    $childClassifys = Classify::wherePid($goodsTwoClassify->pid)->get();
                }else{
                    $classify->classify_two_id = 0;

                    if($classify->classify_id){
                        $childClassifys = classify::wherePid($classify->classify_id)->get();
                    }
                }
            }else{
                $childClassifys = null;
            }
        }else{
            $childClassifys = null;
        }

        return view('admin.section-set',['banner' => $classify,"parent_classifys"=>$parentClassifys,"child_classifys"=>$childClassifys]);
    }

    public function goodsList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $keyword  = $request->get('keyword');
        $classify_id  = $request->get('classify_id');
        $classify_two_id  = $request->get('classify_two_id');
        $goods = Goods::whereType('common');
        if ($keyword){
            $goods=$goods->where('name','like','%'.$keyword.'%')
                ->orwhere('ssn','like','%'.$keyword.'%');
        }
        if ($classify_id){
            $goods=$goods->where('classify_id','=',$classify_id);
        }
        if ($classify_two_id){
            $goods=$goods->where('classify_two_id','=',$classify_two_id);
        }

        /** @var Goods $good */
        $goods = $goods->orderBy('created_at','desc')->paginate(30);
        if(count($goods) > 0){
            foreach($goods as $good){
                $good->thumb_url = FileManager::getImgUrl($good->thumb_id);

                /** @var Classify $thisClassify */
                $thisClassify = Classify::whereId($good->classify_id)->first();
                if($thisClassify){
                    $good->classify_name = $thisClassify->name;
                }else{
                    $good->classify_name = '-';
                }
            }
        }
        $classify = Classify::whereType("goods")->get();
        $classify_two = Classify::whereType("goods")->where('pid','>',0)->get();

        return view('admin.goods-list',['goods' => $goods,'keyword'=>$keyword,'classify_id'=>$classify_id,'classifies'=>$classify,'classifies_two'=>$classify_two,'classify_two_id'=>$classify_two_id]);
    }

    public function goodsSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $sysGoods = Goods::whereId($id)->first();
        if($sysGoods){
            $sysGoods->thumb_url = FileManager::getImgUrl($sysGoods->thumb_id);
        }

        $parentClassifys = Classify::wherePid(0)->whereType("goods")->get();
        if($sysGoods){
            $goodsTwoClassify = Classify::whereId($sysGoods->classify_two_id)->first();
            if($goodsTwoClassify){
                $childClassifys = Classify::wherePid($goodsTwoClassify->pid)->get();
            }else{
                $childClassifys = null;

                if($sysGoods->classify_id){
                    $childClassifys = classify::wherePid($sysGoods->classify_id)->get();
                }
            }
        }else{
            $childClassifys = null;
        }
        $rules=DiscountSalesRule::all();
        $exist_rule_ids=DiscountXGoods::whereGoodsId($id)->pluck('discount_sales_rule_id')->toArray();

        return view('admin.goods-set',['sysGoods' => $sysGoods,"parent_classifys"=>$parentClassifys,"child_classifys"=>$childClassifys,'rules'=>$rules,'exist_rule_ids'=>$exist_rule_ids]);
    }

    public function goodsIntegralList(){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        /** @var Goods $good */
        $goods = Goods::whereType('integral')->orderBy('created_at','desc')->paginate(30);
        if(count($goods) > 0){
            foreach($goods as $good){
                $good->thumb_url = FileManager::getImgUrl($good->thumb_id);

                /** @var Classify $thisClassify */
                $thisClassify = Classify::whereId($good->classify_id)->first();
                if($thisClassify){
                    $good->classify_name = $thisClassify->name;
                }else{
                    $good->classify_name = '-';
                }
            }
        }

        return view('admin.goods-integral-list',['goods' => $goods]);
    }


    public function goodsIntegralSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $sysGoods = Goods::whereId($id)->first();
        if($sysGoods){
            $sysGoods->thumb_url = FileManager::getImgUrl($sysGoods->thumb_id);
        }

        $classifys = Classify::get();

        return view('admin.goods-integral-set',['sysGoods' => $sysGoods,'classifys' => $classifys]);
    }


    public function goodsBannerList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $goodsId = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var GoodsBanner $goodsBanner */
        $goodsBanners = GoodsBanner::whereGoodsId($goodsId)->get();
        if(count($goodsBanners) > 0){
            foreach($goodsBanners as $goodsBanner){
                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereId($goodsBanner->goods_id)->first();
                if($thisGoods){
                    $goodsBanner->goods_name = $thisGoods->name;
                }else{
                    $goodsBanner->goods_name = '-';
                }

                $goodsBanner->img_url = FileManager::getImgUrl($goodsBanner->img_id);
            }
        }

        return view('admin.goods-banner-list',['goodsBanners' => $goodsBanners,'goodsId' => $goodsId]);
    }

    public function goodsImgList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $goodsId = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var GoodsImg $goodsImg */
        $goodsImgs = GoodsImg::whereGoodsId($goodsId)->get();
        if(count($goodsImgs) > 0){
            foreach($goodsImgs as $goodsImg){
                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereId($goodsImg->goods_id)->first();
                if($thisGoods){
                    $goodsImg->goods_name = $thisGoods->name;
                }else{
                    $goodsImg->goods_name = '-';
                }

                $goodsImg->thumb_url = FileManager::getImgUrl($goodsImg->thumb_id);
            }
        }

        return view('admin.goods-img-list',['goodsImgs' => $goodsImgs,'goodsId' => $goodsId]);
    }

    public function ordersList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $orderNum  = $request->get('order_num');
        $startTime = $request->get('start_time');
        $endTime   = $request->get('end_time');
        $status   = $request->get('status');

        $orders = DB::table('orders')->whereNull('deleted_at');

        if(!is_null($orderNum) && $orderNum != ''){
//            $orders->whereOrderNum($orderNum);
            $address_ids=OrderAddress::where('phone','like','%'.trim($orderNum).'%')->orWhere('consignee','like','%'.trim($orderNum).'%')->pluck('id')->toArray();
            $address_ids=array_unique($address_ids);
            $orders->whereOrderNum($orderNum)->orWhereIn('address_id',$address_ids);
        }

        if((!is_null($startTime) && $startTime != '') && (!is_null($endTime) && $endTime != '')){
            $orders = $orders->whereBetween('created_at',[$startTime,$endTime]);
        }

        if ($status){
            $orders = $orders->whereStatus($status);
        }

        $orders = $orders->orderBy('created_at','desc')->paginate(30);
        if(count($orders) > 0){
            foreach($orders as $order){
                /** @var UserInfo $thisUserInfo */
                $thisUserInfo = UserInfo::whereUserId($order->user_id)->first();
                if($thisUserInfo){
                    $order->nickname  = $thisUserInfo->nickname;
                    $order->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                }else{
                    $order->nickname  = null;
                    $order->photo_url = null;
                }

                /** @var OrderAddress $userAddress */
                $userAddress = OrderAddress::whereId($order->address_id)->first();
                if($userAddress){
//                    $order->Address  = $userAddress->province.$userAddress->city.$userAddress->area.$userAddress->address;
                    $order->Address  = trim($userAddress->address);
                    $order->name     = $userAddress->consignee;
                    $order->phone    = $userAddress->phone;
                    $order->postcode = $userAddress->postcode;
                }else{
                    $order->Address = null;
                    $order->name     = '';
                    $order->phone    = '';
                    $order->postcode = '';
                }
            }
        }

        /** @var Express $thisExpress */
        $thisExpress = Express::get();

        return view('admin.orders-list',['orders' => $orders,'orderNum' => $orderNum,'startTime' => $startTime,'endTime' => $endTime,'thisExpress' => $thisExpress,'status'=>$status]);
    }

    public function ordersDetails(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;
        /** @var Orders $thisOrder */
        /** @var Orders $order */
        $order = Orders::whereId($id)->first();
        if($order){
            /** @var UserInfo $thisUserInfo */
            $thisUserInfo = UserInfo::whereUserId($order->user_id)->first();
            if($thisUserInfo){
                $order->nickname  = $thisUserInfo->nickname;
                $order->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
            }else{
                $order->nickname  = null;
                $order->photo_url = null;
            }

            /** @var Express $thisExpress */
            $thisExpress = Express::whereId($order->express)->first();
            if($thisExpress){
                $order->express_name = $thisExpress->name;
            }else{
                $order->express_name = null;
            }

            /** @var OrderAddress $userAddress */
            $userAddress = OrderAddress::whereId($order->address_id)->first();
            if($userAddress){
                $order->address = $userAddress->province.$userAddress->city.$userAddress->area.$userAddress->address;
                $order->consignee = $userAddress->consignee;
                $order->phone   = $userAddress->phone;
            }else {
                $order->address = null;
            }
            if ($order->pay_type=='balance'){
                $balance=ChargeAvailable::whereUserId($order->user_id)->first();
                if ($balance){
                    $discount=DiscountRule::whereId($balance->discount_rule_id)->first();
                } else {
                    $discount=false;
                }
                $discount=$discount ? $discount->rule_name: '无折扣';
            } else {
                $discount='无折扣';
            }
            $order->discount=$discount;

        }
        $total_num=0;

        /** @var OrderItem $orderItem */
        $orderItems = OrderItem::whereOrderId($id)->get();
        if(count($orderItems) > 0){
            foreach($orderItems as $orderItem){
                /** @var Goods $thisGoods */
                $thisGoods = GoodsSnapshot::whereId($orderItem->goods_snapshot_id)->first();
                $tmpGoods  = Goods::whereId($orderItem->goods_id)->first();
                if($thisGoods){
                    $orderItem->goods_name = $thisGoods->name;
                    if ($tmpGoods){
                        /** @var Classify $classify */
                        $classify = Classify::whereId($tmpGoods->classify_id)->first();
                        if($classify){
                            $orderItem->classify_name = $classify->name;
                        }else{
                            $orderItem->classify_name = null;
                        }
                    }

                }else{
                    $orderItem->goods_name = null;
                    $orderItem->classify_name = null;
                }
                $spu_info=GoodsSpu::whereId($orderItem->goods_spu_id)->first();
                $orderItem->spu_info=$spu_info ? $spu_info : null;
                $total_num=$total_num + $orderItem->num;

            }
            if ($order){
                $order->total_num=$total_num;
            }
        }

        return view('admin.orders-details',['thisOrder' => $order,'orderItems' => $orderItems]);
    }

    public function writeShipInfo(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $orderId = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var Orders $thisOrder */
        $thisOrder = Orders::whereId($orderId)->first();
        if($thisOrder){
            /** @var UserAddress $userAddress */
            $userAddress = OrderAddress::whereId($thisOrder->address_id)->first();
            if($userAddress){
                $thisOrder->Address  = $userAddress->province.$userAddress->city.$userAddress->area.$userAddress->add_detail;
                $thisOrder->name     = $userAddress->consignee;
                $thisOrder->phone    = $userAddress->phone;
                $thisOrder->postcode = $userAddress->postcode;
            }else{
                $thisOrder->Address = null;
            }
        }

        /** @var Express $thisExpress */
        $thisExpress = Express::get();

        return view('admin.write-ship-info',['thisOrder' => $thisOrder,'thisExpress' => $thisExpress]);
    }

    public function goodsCommentList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $goodsId = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;

        /** @var Comment $comment */
        $comments = Comment::whereGoodsId($goodsId)->orderBy('created_at','desc')->paginate(30);
        if(count($comments) > 0){
            foreach($comments as $comment){
                $comment->photo_url = FileManager::getImgUrl($comment->photo_id );
                /** @var UserInfo $thisUserInfo */
                $thisUserInfo = UserInfo::whereUserId($comment->user_id)->first();
                if($thisUserInfo){
                    $comment->nickname = $thisUserInfo->nickname;
                    $comment->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id );
                }

                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereId($comment->goods_id)->first();

                $comment->goods_name= $thisGoods    ? $thisGoods->name : '谁叫你删的';
            }
        }

        return view('admin.goods-comment-list',['comments' => $comments,'goodsId' => $goodsId]);
    }

    public function goodsCommentSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $goodsId = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;

        return view('admin.goods-comment-set',['goodsId' => $goodsId]);
    }

    public function goodsCommentImgList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $commentId = !is_null($request->get('id')) ? $request->get('id') :0;

        $goodsId = $request->get('goods_id');

        /** @var CommentImg $commentImg */
        $commentImgs = CommentImg::whereCommentId($commentId)->get();
        if(count($commentImgs) > 0){
            foreach($commentImgs as $commentImg){
                $commentImg->img_url = FileManager::getImgUrl($commentImg->img_id);
            }
        }

        return view('admin.goods-comment-img-list',['commentImgs' => $commentImgs,'goodsId' => $goodsId,'commentId' => $commentId]);
    }

    public function couponsList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $coupons = Coupons::orderBy('created_at','desc')->paginate(20);

        if(count($coupons)>0){
            foreach($coupons as $coupon){

                $coupon->img_url=FileManager::getImgUrl($coupon->img_id);
            }
        }



        return view('admin.coupons-list',['coupons' => $coupons]);
    }

    public function couponsSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisCoupon = Coupons::whereId($id)->first();

        return view('admin.coupons-set',['thisCoupon' => $thisCoupon]);
    }

    public function changePwd(){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        return view('admin.change-psw');
    }

    public function bannerNavList(){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $sysBanners = BannerNav::orderBy('created_at','desc')->get();

        return view('admin.banner-nav-list',['banners'=>$sysBanners]);
    }
    public function bannerNavSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        $thatBanner = BannerNav::whereId($id)->first();

        return view('admin.banner-nav-set',['banner'=>$thatBanner]);
    }

    public function goodsSpuList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $goodsId = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $type = 'goods';
        if (!$goodsId){
            echo '参数错误。访问本页面，建议在商品列表中点击“属性”进入';die();
        }

        /** @var GoodsSpu $goods */
        $goodsSpu = GoodsSpu::whereGoodsId($goodsId)->orderBy('sort','asc')->paginate(100);
        if(count($goodsSpu) > 0){
            foreach($goodsSpu as $goods){
                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereId($goods->goods_id)->first();
                if($thisGoods){
                    $goods->goods_name = $thisGoods->name;
                    $goods->thumb_url  = FileManager::getImgUrl($goods->img_id);
                }else{
                    $goods->goods_name = null;
                    $goods->thumb_url  = null;
                }
            }
        }

        return view('admin.goods-spu-list',['goodsSpu' => $goodsSpu,'goodsId' => $goodsId,'type' => $type]);
    }

    public function goodsSpuSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id      = !is_null($request->get('id')) ? $request->get('id') : 0;
        $goodsId = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $type    = 'goods';

        $thisGoodsSpu = GoodsSpu::whereId($id)->whereGoodsId($goodsId)->first();
        $value   = GoodsSpu::orderBy('id','desc')->first();

        return  view('admin.goods-spu-set',['thisGoodsSpu' => $thisGoodsSpu,'goodsId' => $goodsId,'type' => $type,'value'=>$value]);
    }

    public function userIntegralList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        /** @var UserIntegralRecord $userInt */
        $userIntegral = UserIntegralRecord::orderBy('created_at','desc')->paginate(30);
        if(count($userIntegral) > 0){
            foreach($userIntegral as $userInt){
                /** @var UserInfo $thisUserInfo */
                $thisUserInfo = UserInfo::whereUserId($userInt->user_id)->first();
                if($thisUserInfo){
                    $userInt->nickname  = $thisUserInfo->nickname;
                    $userInt->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                }else{
                    $userInt->nickname  = null;
                    $userInt->photo_url = null;
                }

                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereId($userInt->goods_id)->first();
                if($thisGoods){
                    $userInt->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                }else{
                    $userInt->thumb_url = null;
                }
            }
        }

        return view('admin.user-integral-list',['userIntegral' => $userIntegral]);
    }

    public function qrCodeList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $qrCodes = QrCodes::orderBy('created_at','desc')->paginate(30);

        return view('admin.qrcode-list',['qrCodes' => $qrCodes]);
    }

    public function qrCodSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisQrCode = QrCodes::whereId($id)->first();

        return view('admin.qrcode-set',['thisQrCode' => $thisQrCode]);
    }

    public function expressCompanyList(){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));
        $express=Express::orderBy('created_at','desc')->paginate(20);

        return view('admin.express-company-list',['express'=>$express]);

    }

    public  function gameRank(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $page = !is_null($request->get("page")) ? $request->get("page") : 1;

        $allUserScores = UserScore::whereNotIn("user_id",[782,761,895,876])->whereBetween("created_at",["2019-05-17 00:00:00","2019-05-28 23:59:59"])->orderBy("score","desc")->paginate(100);

        foreach ($allUserScores as $allUserScore){
            /** @var UserScore $allUserScore */
            $goldNumCount       = UserScoreRecord::whereUserId($allUserScore->user_id)->sum("gold_num");
            $gameScoreCount     = UserScoreRecord::whereUserId($allUserScore->user_id)->whereIn("type",["game","share_relive"])->sum("score");
            $exchangeScoreCount = UserScoreRecord::whereUserId($allUserScore->user_id)->whereType("exchange")->sum("score");

            $allUserScore->gold_num = $goldNumCount;
            $allUserScore->exchange_score = $exchangeScoreCount;
            $allUserScore->score = (int)$gameScoreCount - (int)$exchangeScoreCount;
            $allUserScore->save();

            $thatUser = User::whereId($allUserScore->user_id)->first();
            if($thatUser){
                $thatUserInfo = UserInfo::whereUserId($thatUser->id)->first();

                if($thatUserInfo){
                    $thatUserInfo->photo_url = FileManager::getImgUrl($thatUserInfo->photo_id);
                    $thatUser->user_info = $thatUserInfo;
                }else{
                    $thatUser->user_info = null;
                }

                $allUserScore->user = $thatUser;
            }else{
                $allUserScore->user = null;
            }
        }

        return view('admin.game.game-rank',["allUserScores"=>$allUserScores,"page"=>$page]);

    }

    public function bargainList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        /** @var ActivityBargain $activityBargain */
        $activityBargains = ActivityBargain::orderBy('created_at','desc')->paginate(20);
        if(count($activityBargains) > 0){
            foreach($activityBargains as $activityBargain){
                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereType('bargain')->whereId($activityBargain->goods_id)->first();
                if($thisGoods){
                    $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                    $activityBargain->goods_info = $thisGoods;
                }else{
                    $activityBargain->goods_info = null;
                }

            }
        }

        return view('admin.activity-bargain-list',['activityBargains' => $activityBargains]);
    }

    public function bargainSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var ActivityBargain $thisActivityBargain */
        $thisActivityBargain = ActivityBargain::whereId($id)->first();
        if($thisActivityBargain){
            $thisGoods = Goods::whereId($thisActivityBargain->goods_id)->whereType('bargain')->first();
            if($thisGoods){
                $thisActivityBargain->goods_info = $thisGoods;
            }else{
                $thisActivityBargain->goods_info = null;
            }
        }

        return view('admin.activity-bargain-set',['thisActivityBargain' => $thisActivityBargain]);
    }

    public function userBargainInitiateList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $nickname  = $request->get('nickname');
        $startTime = $request->get('start_time');
        $endTime   = $request->get('end_time');

        /** @var ActivityBargainInitiate $activityBargainInitiate */
        $activityBargainInitiates = ActivityBargainInitiate::orderBy('created_at','desc');

        if(!is_null($nickname) && $nickname != ''){
            $userIds = UserInfo::where('nickname','like','%'.$nickname.'%')->pluck('user_id');

            $activityBargainInitiates->whereIn('user_id',$userIds);
        }

        if(!is_null($startTime) && $startTime != '' && !is_null($endTime) && $endTime != ''){
            $activityBargainInitiates = $activityBargainInitiates->whereBetween('created_at',[$startTime,$endTime]);
        }


        $activityBargainInitiates = $activityBargainInitiates->paginate(20);
        if(count($activityBargainInitiates) > 0){
            foreach($activityBargainInitiates as $activityBargainInitiate){
                /** @var UserInfo $thisUserInfo */
                $thisUserInfo = UserInfo::whereUserId($activityBargainInitiate->user_id)->first();
                if($thisUserInfo){
                    $activityBargainInitiate->nickname  = $thisUserInfo->nickname;
                    $activityBargainInitiate->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                }else{
                    $activityBargainInitiate->nickname  = null;
                    $activityBargainInitiate->photo_url = null;
                }

                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereId($activityBargainInitiate->goods_id)->first();
                if($thisGoods){
                    $activityBargainInitiate->goods_name = $thisGoods->name;
                    $activityBargainInitiate->thumb_url  = FileManager::getImgUrl($thisGoods->thumb_id);
                }else{
                    $activityBargainInitiate->goods_name = null;
                    $activityBargainInitiate->thumb_url  = null;
                }
            }
        }

        return view('admin.user-bargain-initiate-list',['activityBargainInitiates' => $activityBargainInitiates,'nickname' => $nickname,'startTime' => $startTime,'endTime' => $endTime]);
    }

    public function userBargainInitiateDetail(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var ActivityBargainInitiate $thisBargainInitiate */
        $thisBargainInitiate = ActivityBargainInitiate::whereId($id)->first();
        if($thisBargainInitiate){
            /** @var UserInfo $thisUserInfo */
            $thisUserInfo = UserInfo::whereUserId($thisBargainInitiate->user_id)->first();
            if($thisUserInfo){
                $thisUserInfo->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                $thisBargainInitiate->user_info = $thisUserInfo;
            }else{
                $thisBargainInitiate->user_info = null;
            }

            /** @var Goods $thisGoods */
            $thisGoods = Goods::whereId($thisBargainInitiate->goods_id)->first();
            if($thisGoods){
                $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                $thisBargainInitiate->goods_info = $thisGoods;
            }else{
                $thisBargainInitiate->goods_info = null;
            }

            $thisGoodsSpu = GoodsSpu::whereGoodsId($thisBargainInitiate->goods_id)->whereId($thisBargainInitiate->goods_spu_id)->first();
            if($thisGoodsSpu){
                $thisBargainInitiate->goods_spu_info = $thisGoodsSpu;
            }else{
                $thisBargainInitiate->goods_spu_info = null;
            }

            $thisBargain = ActivityBargain::whereId($thisBargainInitiate->ab_id)->first();
            if($thisBargain){
                $thisBargainInitiate->activity_bargain_info = $thisBargain;
            }else{
                $thisBargainInitiate->activity_bargain_info = null;
            }
        }

        return view('admin.user-bargain-initiate-detail',['thisBargainInitiate' => $thisBargainInitiate]);
    }

    public function userBargainJoinList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var ActivityBargainJoin $activityBargainJoin */
        $activityBargainJoins = ActivityBargainJoin::whereAbiId($id)->orderBy('created_at','desc')->paginate(20);
        if(count($activityBargainJoins) > 0){
            foreach($activityBargainJoins as $activityBargainJoin){
                /** @var UserInfo $thisUserInfo */
                $thisUserInfo = UserInfo::whereUserId($activityBargainJoin->user_id)->first();
                if($thisUserInfo){
                    $activityBargainJoin->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                    $activityBargainJoin->nickname  = $thisUserInfo->nickname;
                }else{
                    $activityBargainJoin->photo_url = null;
                    $activityBargainJoin->nickname  = null;
                }
            }
        }

        return view('admin.user-bargain-join-list',['activityBargainJoins' => $activityBargainJoins,'abi_id' => $id]);
    }

    public function GroupList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        /** @var ActivityGroup $activityGroup */
        $activityGroups = ActivityGroup::orderBy('created_at','desc')->paginate(20);
        if(count($activityGroups) > 0){
            foreach($activityGroups as $activityGroup){
                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereType('group')->whereId($activityGroup->goods_id)->first();
                if($thisGoods){
                    $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                    $activityGroup->goods_info = $thisGoods;
                }else{
                    $activityGroup->goods_info = null;
                }

            }
        }

        return view("admin.activity-group-list",['activityGroups' => $activityGroups]);
    }

    public function GroupSet(Request $request)
    {
        if (Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var ActivityGroup $thisActivityGroup */
        $thisActivityGroup = ActivityGroup::whereId($id)->first();
        if ($thisActivityGroup) {
            $thisGoods = Goods::whereId($thisActivityGroup->goods_id)->whereType('group')->first();
            if ($thisGoods) {
                $thisActivityGroup->goods_info = $thisGoods;
            } else {
                $thisActivityGroup->goods_info = null;
            }
        }

        return view('admin.activity-group-set',['thisActivityGroup' => $thisActivityGroup]);
    }

    public function groupGoodsSpuList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $goodsId         = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $activityGroupId = !is_null($request->get('activity_group_id')) ? $request->get('activity_group_id') : 0;
        $type = 'group';

        /** @var GoodsSpu $goods */
        $goodsSpu = GoodsSpu::whereGoodsId($goodsId)->paginate(30);
        if(count($goodsSpu) > 0){
            foreach($goodsSpu as $goods){
                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereId($goods->goods_id)->whereType($type)->first();
                if($thisGoods){
                    $goods->goods_name = $thisGoods->name;
                    $goods->thumb_url  = FileManager::getImgUrl($thisGoods->thumb_id);
                }else{
                    $goods->goods_name = null;
                    $goods->thumb_url  = null;
                }

                /** @var ActivityGroupPrice $activityGroupPrice */
                $activityGroupPrice = ActivityGroupPrice::whereActivityGroupId($activityGroupId)->whereGoodsId($goods->goods_id)->whereGoodsSpuId($goods->id)->first();
                if($activityGroupPrice){
                    $goods->many_price = $activityGroupPrice->many_price;
                }else{
                    $goods->many_price = 0.00;
                }
            }
        }

        return view('admin.goods-spu-list',['goodsSpu' => $goodsSpu,'goodsId' => $goodsId,'type' => $type,'activityGroupId' => $activityGroupId]);
    }

    public function groupGoodsSpuSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id      = !is_null($request->get('id')) ? $request->get('id') : 0;
        $goodsId = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $activityGroupId = !is_null($request->get('activity_group_id')) ? $request->get('activity_group_id') : 0;
        $type = 'group';

        $thisGoodsSpu = GoodsSpu::whereId($id)->whereGoodsId($goodsId)->first();
        if($thisGoodsSpu){
            /** @var ActivityGroupPrice $activityGroupPrice */
            $activityGroupPrice = ActivityGroupPrice::whereActivityGroupId($activityGroupId)->whereGoodsId($thisGoodsSpu->goods_id)->whereGoodsSpuId($thisGoodsSpu->id)->first();
            if($activityGroupPrice){
                $thisGoodsSpu->many_price = $activityGroupPrice->many_price;
            }else{
                $thisGoodsSpu->many_price = 0.00;
            }
        }

        return  view('admin.goods-spu-set',['thisGoodsSpu' => $thisGoodsSpu,'goodsId' => $goodsId,'type' => $type,'activityGroupId' => $activityGroupId]);
    }

    public function groupAddList(Request $request){
        if (Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $nickname  = $request->get('nickname');
        $startTime = $request->get('start_time');
        $endTime   = $request->get('end_time');

        /** @var ActivityGroupAdd $groupAdd */
        $groupAddList = ActivityGroupAdd::whereGroupId(0);

        if(!is_null($nickname) && $nickname != ''){
            $userIds = UserInfo::where('nickname','like','%'.$nickname.'%')->pluck('user_id');

            $groupAddList->whereIn('user_id',$userIds);
        }

        if(!is_null($startTime) && $startTime != '' && !is_null($endTime) && $endTime != ''){
            $groupAddList = $groupAddList->whereBetween('created_at',[$startTime,$endTime]);
        }

        $groupAddList = $groupAddList->orderBy('created_at','desc')->paginate(30);
        if(count($groupAddList) > 0){
            foreach($groupAddList as $groupAdd){
                /** @var UserInfo $thisUserInfo */
                $thisUserInfo = UserInfo::whereUserId($groupAdd->user_id)->first();
                if($thisUserInfo){
                    $groupAdd->nickname  = $thisUserInfo->nickname;
                    $groupAdd->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                }else{
                    $groupAdd->nickname  = null;
                    $groupAdd->photo_url = null;
                }

                /** @var ActivityGroup $thisActivityGroup */
                $thisActivityGroup = ActivityGroup::whereId($groupAdd->ag_id)->first();
                if($thisActivityGroup){
                    /** @var Goods $thisGoods */
                    $thisGoods = Goods::whereId($thisActivityGroup->goods_id)->first();
                    if($thisGoods){
                        $groupAdd->goods_name      = $thisGoods->name;
                        $groupAdd->goods_thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                    }else{
                        $groupAdd->goods_name      = null;
                        $groupAdd->goods_thumb_url = null;
                    }
                }else{
                    $groupAdd->goods_name      = null;
                    $groupAdd->goods_thumb_url = null;
                }
            }
        }

        return view('admin.user-group-add-list',['groupAddList' => $groupAddList,'nickname' => $nickname,'startTime' => $startTime,'endTime' => $endTime]);
    }

    public function groupAddMemberList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $groupId = !is_null($request->get('group_id')) ? $request->get('group_id') : 0;

        /** @var ActivityGroupAdd $groupAddMember */
        $groupAddMemberList = ActivityGroupAdd::whereGroupId($groupId)->orderBy('created_at','desc')->get();
        if(count($groupAddMemberList) > 0){
            foreach($groupAddMemberList as $groupAddMember){
                /** @var UserInfo $thisUserInfo */
                $thisUserInfo = UserInfo::whereUserId($groupAddMember->user_id)->first();
                if($thisUserInfo){
                    $groupAddMember->nickname  = $thisUserInfo->nickname;
                    $groupAddMember->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                }else{
                    $groupAddMember->nickname  = null;
                    $groupAddMember->photo_url = null;
                }

                /** @var ActivityGroup $thisActivityGroup */
                $thisActivityGroup = ActivityGroup::whereId($groupAddMember->ag_id)->first();
                if($thisActivityGroup){
                    /** @var Goods $thisGoods */
                    $thisGoods = Goods::whereId($thisActivityGroup->goods_id)->first();
                    if($thisGoods){
                        $groupAddMember->goods_name      = $thisGoods->name;
                        $groupAddMember->goods_thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                    }else{
                        $groupAddMember->goods_name      = null;
                        $groupAddMember->goods_thumb_url = null;
                    }
                }else{
                    $groupAddMember->goods_name      = null;
                    $groupAddMember->goods_thumb_url = null;
                }
            }
        }

        return view('admin.user-group-add-member-list',['groupAddMemberList' => $groupAddMemberList]);
    }

    public function discountList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));
        $rules=DiscountRule::all();

        return  view('admin.discount-list',['rules' => $rules]);

    }

    public function downLoadExcel(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));
        $start_time     =$request->get('start_time');
        $end_time       =$request->get('end_time');
        $order_num      =$request->get('order_num');

        $order_status   =$request->get('status');

        $orders=Orders::orderBy('id','desc');
        if ($start_time && $end_time){
            $orders = $orders->whereBetween('created_at',[$start_time,$end_time]);
        }
        if ($order_num){
            $orders = $orders->whereOrderNum($order_num);
        }

        if ($order_status){
            $orders = $orders->whereStatus($order_status);
        }
        $fileName='订单导出-'.$start_time.'至'.$end_time.'--'.rand(1000,9999);
        $data=[];
//        $temp=['ID','订单号','子订单号','姓名','手机','收货地址','商品编码','规格编码','尺码','颜色','商品名称','商品数量','商品类型','订单状态','备注','商品优惠','会员折扣','邮费','本件单价','实付金额'];
//        $temp=['下单日期*','店铺代码*','交易号*','会员昵称*','收货人*','手机号*','固定电话','收货地址*','邮编','是否货到付款','付款日期','仓库代码','配送方式代码','运费','买家留言','商家留言','商品条形码*','单价','数量*','仓库留言','订单备注'];
        $temp=[
            '日期1','店铺代码2*','交易号3*',
            '用户昵称4*','收货人5*','手机号6*',
            '电话7','邮箱8', '顾客地址省9',
            '顾客地址市10','县/区11','详细地址12*',
            '邮编13','支付方式14*','快递公司15*',
            '发货仓库16','运费17','其他折扣18',
            '商家备注19（导出的是买家留言）', '款号20','SKU21*',
            '颜色代码22','颜色名称23','尺码代码24',
            '尺码名称25','售价26','单价27*',
            '数量28*', '物流单号29','是否礼品30',
            '是否套餐31','发票类型32','发票抬头33','发票支付方式34','发票金额35','发票内容36',
            '发票号37','发票税号38','返回错误日志'
            ];
        array_push($data,$temp);
        unset($temp);
        $orders=$orders->get();
        if (count($orders) > 0){
            /** @var Orders $order */
            foreach ($orders as $order){
                $thisUserDiscount=ChargeAvailable::whereUserId($order->user_id)->first();
                if ($thisUserDiscount)
                    $rule=DiscountRule::whereId($thisUserDiscount->discount_rule_id)->first();
                else
                    $rule=null;
//                if($order->status == 1){
//                    $statusType = '待付款';
//                }elseif($order->status == 2){
//                    $statusType = '待发货';
//                }elseif($order->status == 3){
//                    $statusType = '待收货';
//                }elseif($order->status == 4){
//                    $statusType = '待评价';
//                }elseif($order->status == 5){
//                    $statusType = '已完成';
//                }elseif($order->status == 6){
//                    $statusType = '已取消';
//                }elseif($order->status == 8){
//                    $statusType = '待分享';
//                } else {
//                    $statusType = '未知';
//                }

                $orderItems=OrderItem::whereOrderId($order->id)->get();
                if (count($orderItems) > 0){

                    /** @var OrderItem $orderItem */
                    foreach ($orderItems as $orderItem){
                        $address=OrderAddress::whereId($order->address_id)->first();
                        $spu    =GoodsSpu::whereId($orderItem->goods_spu_id)->first();
                        $shot   =GoodsSnapshot::whereId($orderItem->goods_snapshot_id)->first();
                        $goods  =Goods::whereId($orderItem->goods_id)->first();
                        $thisUser=UserInfo::whereUserId($order->user_id)->first();
//                        if ($goods)
//                            $classify = Classify::whereId($goods->classify_id)->first();
//                        else
//                            $classify = false;
//                        if($classify){
//                            $classify_name = $classify->name;
//                        }else{
//                            $classify_name = '未知';
//                        }
//                        $goods_discount=(array)json_decode($orderItem->discount_note);
//                        $good_discount_name=$goods_discount ? array_pop($goods_discount['name']) : '';
//                        $temp=[
//                            $order->id,
//                            $order->order_num,
//                            $orderItem->item_num,
//                            $address->consignee,
//                            $address->phone,
//                            $address->province.$address->city.$address->area.$address->address,
//                            $shot ? $shot->ssn : '未知',
//                            $spu ? $spu->specification_code : '未知',
//                            $spu ? $spu->size_spu_name  : '未知',
//                            $spu ? $spu->color_spu_name : '未知',
//                            $shot ? $shot->name : $shot->name,
//                            $orderItem->num,
//                            $classify_name,
//                            $statusType,
//                            $order->note,
//                            $good_discount_name,
//                            $rule ? $rule->rule_name : '无',
//                            $order->express_fee,
//                            round($orderItem->s_price * ($rule ? $rule->rate : 1),2),
//                            $order->s_amount
//                        ];
                        $temp=[
                            date_format($order->created_at,'Y-m-d'),
                            'ht004',
                            $order->order_num,
                            $thisUser   ? $thisUser->nickname   : '无记录',
                            $address    ? $address->consignee   : '无记录',
                            $address    ? $address->phone       : '无记录',
                            '',
                            $address ? ($address->province.$address->city.$address->area.' '.$address->address) : '无记录',
                            $address ? ($address->postcode ? $address->postcode : '')                           : '无记录',
                            '',
                            $order->is_pay ? date('Y-m-d',strtotime($order->pay_time)) : '导出时未付款',
                            '001',
                            'ZTO',
                            $order->express_fee,
                            $order->note,
                            '',
                            $spu ? $spu->specification_code : '',
                            $orderItem->s_price * ($order->vip_discount_rate!=0 ? $order->vip_discount_rate : ($rule ? $rule->rate : 1)),
                            $orderItem->num,
                            '',
                            ''
                        ];
                        $tmp='';
                        if ($orderItem->discount_note){
                            $orderItem->discount_note=json_decode($orderItem->discount_note);
                            if (isset($orderItem->discount_note->name))
                            foreach($orderItem->discount_note->name as $item){
                                $tmp=$tmp.$item;
                            }
                        }

                        $temp=[
                            $order->created_at,'ht004',$order->order_num,
                            $thisUser ? ($thisUser->nickname ? $thisUser->nickname : '昵称为空')  : '找不到用户',$address ? $address->consignee : '',$address ? $address->phone : '',
                            '','',$address ? $address->province : '',
                            $address ? $address->city : '',$address ? $address->area :'',$address ? $address->address : '',
                            $address ? ($address->postcode ? $address->postcode : '') : '',$order->is_pay ? 'alipay' : '','ZTO',
                            '001',$order->express_fee,($order->vip_discount_note ? $order->vip_discount_note : '').($orderItem->discount_note ? $tmp: ''),
                            $order->note,'',$spu ? $spu->specification_code : '',
                            '',$spu ? $spu->color_spu_name : '','',
                            $spu ? $spu->size_spu_name : '',$spu ? $spu->price : 0.00,$orderItem->s_price * ($order->vip_discount_rate!=0 ? $order->vip_discount_rate : ($rule ? $rule->rate : 1)),
                            $orderItem->num,$order->express_num,($orderItem->s_price==0) ? 1 : '',
                            '','','','','','',
                            '','',''
                        ];
                        array_push($data,$temp);
                    }
                }
            }
        }
        Excel::create($fileName,function($excel) use($data){
            $excel->sheet('订单信息',function ($sheet) use ($data){
                $sheet->fromArray($data,null,'A1',true,false);
            });
        })->download('xls');

    }

    public function discountSalesList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));
        $rules=DiscountSalesRule::orderBy('id','desc')->paginate(30);

        return view('admin.discount-sales-list',['rules' => $rules]);
    }
    public function setDiscountSales(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));
        $id=$request->get('id');
        $rules=DiscountSalesRule::whereId($id)->first();
        return view('admin.discount-sales-set',['thisRule' => $rules]);
    }

    public function getExpressBladeList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));
        $blades=ExpressBlade::orderBy('is_default','desc')->orderBy('id','desc')->paginate(30);
        return view('admin.express-blade-list',['blades' => $blades]);
    }
    public function getExpressCustomList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));
        $blade_id=$request->get('blade_id');
        $record=ExpressCustomFee::whereExpressBladeId($blade_id)->orderBy('id','desc')->paginate(30);
        $thisBlade=ExpressBlade::whereId($blade_id)->first();
        return view('admin.express-fee-list',['fees' => $record,'this_blade'=>$thisBlade]);
    }

    public function getOrderRefundApply(Request $request)
    {
        if (Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));
        /** @var OrderRefund $applies */
        $applies = OrderRefund::orderBy('status', 'asc')->paginate(30);
        if (count($applies) > 0) {
            /** @var OrderRefund $apply */
            foreach ($applies as $apply) {
                $order = Orders::whereOrderNum($apply->order_num)->first();
                if ($order) {
                    /** @var UserInfo $thisUserInfo */
                    $thisUserInfo = UserInfo::whereUserId($order->user_id)->first();
                    if ($thisUserInfo) {
                        $order->nickname = $thisUserInfo->nickname;
                        $order->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                    } else {
                        $order->nickname = null;
                        $order->photo_url = null;
                    }

                    /** @var OrderAddress $userAddress */
                    $userAddress = OrderAddress::whereId($order->address_id)->first();
                    if ($userAddress) {
                        $order->Address = $userAddress->province . $userAddress->city . $userAddress->area . $userAddress->address;
                        $order->name = $userAddress->consignee;
                        $order->phone = $userAddress->phone;
                        $order->postcode = $userAddress->postcode;
                    } else {
                        $order->Address = null;
                        $order->name = '';
                        $order->phone = '';
                        $order->postcode = '';

                    }
                }
                $apply->orders = $order;
            }
        }
        $address=ReturnAddress::first();
        if (!$address){
            $address=new ReturnAddress();
            $address->name='收货人';
            $address->phone='联系电话';
            $address->address='地址';
            $address->save();
        }


        return view('admin.orders-refund', ['applies' => $applies,'address'=>$address]);

    }
    public function getUserChargeRecord(Request $request){
        if (Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));
        $user_id=$request->get('user_id');
        $type   =$request->get('type');

        if ($user_id){
            $records = ChargeRecord::whereUserId($user_id)->orderBy('id','desc')->paginate(50);
            if ($type=='used'){
                $records = ChargeUsedRecord::whereUserId($user_id)->orderBy('id','desc')->paginate(50);
            }
        } else {
            $records = ChargeRecord::orderBy('id','desc')->paginate(50);
        }
        if (count($records) > 0){
            /** @var ChargeRecord $record */
            foreach ($records as $record){
                $userInfo=UserInfo::whereUserId($record->user_id)->first();
                $user   =User::whereId($record->user_id)->first();
                $record->nickname=$userInfo ? $userInfo->nickname : '';
                $record->phone=$user ? $user->phone : '';
            }
        }
        return view('admin.charge-detail',['detail'=>$records,'user_id'=>$user_id,'type'=>$type]);

    }

    public function shopList(){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        /** @var Shops $shop */
        $shops = Shops::orderBy('created_at','desc')->paginate(30);
        if(count($shops) > 0){
            foreach ($shops as $shop) {
                $shop->thumb_url = FileManager::getImgUrl($shop->thumb_id);
            }
        }

        return view('admin.shop-list',['shops'=>$shops]);
    }

    public function shopSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        $shop = Shops::whereId($id)->first();
        if($shop){
            $shop->thumb_url = FileManager::getImgUrl($shop->thumb_id);
        }

        return view('admin.shop-set',['shop'=>$shop]);
    }
}